

package com.coding4play.mqtt.store.impl;

import com.coding4play.mqtt.common.entity.message.DupPubRelMessage;
import com.coding4play.mqtt.common.repository.IDupPubRelMessageRepository;
import com.coding4play.mqtt.store.config.RedisTemplateWrapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class DupPubRelMessageRepositoryImpl extends RedisTemplateWrapper implements IDupPubRelMessageRepository {

    private final static String HASH_DUP_PUBLISH_REL_PRE = "mqtt:publish_rel:clientId_msgId_msg:";

    public DupPubRelMessageRepositoryImpl(RedisTemplate<String, Object> redisTemplate) {
        super(redisTemplate);
    }

    @Override
    public void put(String clientId, DupPubRelMessage dupPubRelMessage) {
        HASH.put(getKey(clientId), dupPubRelMessage.getMessageId().toString(), dupPubRelMessage);
    }

    @Override
    public List<DupPubRelMessage> get(String clientId) {
        if (!redisTemplate.hasKey(getKey(clientId))) {
            return Collections.emptyList();
        }

        List<DupPubRelMessage> collect = HASH.values(getKey(clientId)).stream()
                .map(msg -> (DupPubRelMessage) msg)
                .collect(Collectors.toList());
        return collect;

    }

    @Override
    public void delete(String clientId, Integer messageId) {
        HASH.delete(getKey(clientId), messageId);
    }

    @Override
    public void delete(String clientId) {
        redisTemplate.delete(getKey(clientId));
    }


    public String getKey(String clientId) {
        return HASH_DUP_PUBLISH_REL_PRE + clientId;
    }
}
